default: help


# 编译设置
CC = gcc                                                    # 编译器
CFLAGS = -Wall -std=c99                                     # 开启所有警告信息,并使用C99标准进行编译
LDFLAGS = -s -w                                             # 剔除编译过程中的符号信息和调试信息(符号表信息用于调试和链接过程,最终会被解析为内存地址和机器指令)
SRC_FILES = $(wildcard src/*.cpp)                             # 查找src目录下所有.c的文件
OBJ_FILES = $(patsubst src/%.c,debug/obj/%.o,$(SRC_FILES))  # 模式替换(如：src/main.c替换为debug/obj/main.o)
TAR_FILE = PhoneBook                                        # 项目/类库/可执行文件名


# 相关依赖条件
.PHONY: _dependencies
_dependencies:
	@mkdir -p ./debug/obj ./debug/bin


# 编译单个文件
debug/obj/%.o: src/%.c _dependencies
	@echo ">> compile file: $@"
    # 编译单个c文件为目标文件(c:编译但不链接; $<:第一个依赖文件,即src/%.c)
	@$(CC) $(CFLAGS) -I ./include -c $< -o $@


## build@编译程序
.PHONY: build
build: $(OBJ_FILES)
	@echo ">> linking files...."
    # 把所有的依赖文件($^即所有的$(OBJ_FILES))链接成最终的可执行文件
	@$(CC) $(LDFLAGS) $^ -o ./debug/bin/$(TAR_FILE)
	@ls -l -h --color=auto ./debug/bin


## run@运行程序
.PHONY: run
run:
    # 条件判断,并递归调用$(MAKE) build以重新构建项目
	@if [ ! -f ./debug/bin/$(TAR_FILE) ]; then $(MAKE) build --no-print-directory; fi
	@./debug/bin/$(TAR_FILE)


## clean@清理缓存和临时文件等
.PHONY: clean
clean:
	@echo ">> cleaning up ..."
	@rm -rf *.exe;
	@rm -rf ./obj;
	@rm -rf ./bin;
	@rm -rf ./logs;
	@rm -rf ./log;
	@rm -rf ./cache;
	@rm -rf ./pid;
	@rm -rf ./release;
	@rm -rf ./debug;
	@rm -rf ./tmp;
	@rm -rf ./temp;
	@rm -rf ./vendor/*;


## help@查看make帮助
.PHONY: help
help: Makefile
	@echo "Usage:  make [command]"
	@echo
	@echo "Available Commands:"
	@sed -n "s/^##//p" $< | column -t -s '@' | grep --color=auto "^[[:space:]][a-z]\+[[:space:]]"
	@echo
	@echo "For more to see https://github.com/hollson"
	@echo
